package com.ugoodtech.mdcc.core.service.impl;

        /* Copyright (C) Ugoodtech, Inc - All Rights Reserved.
         * Unauthorized copying of this file, via any medium is strictly prohibited.
         * Proprietary and confidential.
         * Written by Stone Shaw.
         */


import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.domain.ModuleAuthority;
import com.ugoodtech.mdcc.core.domain.QRole;
import com.ugoodtech.mdcc.core.domain.Role;
import com.ugoodtech.mdcc.core.exception.VStarException;
import com.ugoodtech.mdcc.core.repository.RoleRepository;
import com.ugoodtech.mdcc.core.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleRepository roleRepository;

    @Override
    public Page<Role> queryRole(Pageable pageable, String type) {
        QRole qRole = QRole.role;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qRole.deleted.eq(false));
        if (StringUtils.isNotEmpty(type)) {
            builder.and(qRole.enabled.eq(true));
        }
//        if (!StringUtils.isEmpty(userNo)) {
//            builder.and(qRole.serialNumber.eq(userNo));
//        }
//        if (!StringUtils.isEmpty(name)) {
//            builder.and(qRole.realName.eq(name));
//        }
        Sort sort = new Sort(Sort.Direction.DESC, "creationTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<Role> roles = roleRepository.findAll(builder, pageable);
        return roles;
    }

    @Override
    public Role createRole(String roleName, Set<ModuleAuthority> moduleAuthorities, String desc) throws VStarException {
        Role role = new Role();
        role.setName(roleName);
        role.setAuthorities(moduleAuthorities);
        role.setDescription(desc);
        return roleRepository.save(role);
    }
}
